package com.example.demoweb.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.example.demoweb.entity.Attachment;

@Service
public class FileupdownUtil {
	@Autowired
	private FtpUtil ftpUtil;
	
	/**
	 * 文件上传
	 * @param file
	 * @param request
	 * @param relaId
	 * @param type
	 * @param dir
	 * @return
	 * @throws Exception 
	 */
	public Attachment saveAttachment(MultipartFile file/*上传文件*/,
			String relaId/*关联业务id*/, String type/*关联类型*/,
			String dir/*附件文件夹下的文件夹名用‘/’隔开可建多级文件夹如：image/cms/appeal*/) throws Exception {
		
		System.out.println("开始");
		Attachment attachment = new Attachment();
		String fileName = file.getOriginalFilename();//获取文件全名
		String extensionName = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀格式名
		attachment.setAttType(type);
		attachment.setRelaId(relaId);
		String uuid = UUIDTool.getUUID();
		attachment.setId(uuid);
		attachment.setAttName(fileName);
		attachment.setActiveFlage("1");
		attachment.setFileType("1");//非压缩类型
		Date date = new Date();
		SimpleDateFormat sdfm = new SimpleDateFormat("yyyyMM");
		SimpleDateFormat sdfs = new SimpleDateFormat("yyyyMMddhhmmss");
		String sdfmStr = sdfm.format(date);
		String sdfsStr = sdfs.format(date);
		attachment.setUplodDate(date);
		//FtpUtil ftpUtil = new FtpUtil();
		ftpUtil.connectFtp();
		try {
			String targetFiles = "attachment/" +dir+"/"+ sdfmStr.substring(0,4)+"/"+sdfmStr.substring(4)+"/" +uuid+"."+extensionName;
			InputStream fis = file.getInputStream();
			if(extensionName.contains("jpg") || extensionName.contains("png")
					|| extensionName.contains("bmp") || extensionName.contains("gif")||extensionName.contains("jpeg")){
				if(file.getSize() > 0){
					BufferedImage src = ImageIO.read(fis);
					double width = src.getWidth();
					double height = src.getHeight();
					BufferedImage image = new BufferedImage(((int)(width*0.7)),((int)(height*0.7)),BufferedImage.TYPE_INT_RGB );
					image.getGraphics().drawImage(src,0,0, ((int)(width*0.7)), ((int)(height*0.7)), null); // 绘制缩小后的图  
					ByteArrayOutputStream bs = new ByteArrayOutputStream();
					ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
					ImageIO.write(image,extensionName,imOut); 
					InputStream is = new ByteArrayInputStream(bs.toByteArray());
					ftpUtil.upload(is, targetFiles);
				}else{
					ftpUtil.upload(fis, targetFiles);
				}
			}else{
				ftpUtil.upload(fis, targetFiles);
			}
			attachment.setFileUrl(targetFiles);
			attachment.setFileName(sdfsStr+fileName.getBytes("utf-8"));
			attachment.setSuffix(file.getContentType());
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ftpUtil.disConFtp();
		}
		return attachment;
	}
	/**
	 * 文件下载
	 * @param response
	 * @param type
	 * @param uid
	 * @throws Exception 
	 */
	public void down(HttpServletResponse response,Attachment attachment) throws Exception {
		//FtpUtil ftpUtil = new FtpUtil();
		ftpUtil.connectFtp();
		attachment.setActiveFlage("1");
		if (!attachment.equals(null)) {
			try {
				InputStream bl = ftpUtil.download(attachment.getFileUrl());
				
				response.addHeader("Content-Disposition", "attachment;filename="+new String((attachment.getAttName()).getBytes("GB2312"),"iso8859-1"));
				response.setContentType("application/octet-stream");	
					 try {
						IOUtils.copy(bl,response.getOutputStream());    
					} catch (IOException e) {
						e.printStackTrace();
					}finally{
						bl.close();
						ftpUtil.disConFtp();
					}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
}
